#include "bolckQueue.hpp"
#include "task.hpp"
#include <pthread.h>
#include <ctime>
#include <unistd.h>


using namespace std;

void *consumer(void *args){
    // BlockQueue<int> *bq = static_cast<BlockQueue<int>*>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);

    sleep(1);
    while(1){

        Task t;
        // 1、从blockqueue获取数据
        bq->pop(&t);
        t();
        // 2、结合某种业务逻辑处理数据
        cout << pthread_self() << "| consumer Task = " << t.formatArg() << t.formatRes() << endl;
        usleep(100000);
    }
}

void *productor(void *args){
    // BlockQueue<int> *bq = static_cast<BlockQueue<int>*>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);

    string opers = "+-*/%";

    while(1){
        //1、通过某种去到获取数据
        int x = rand() % 100 + 1;
        int y = rand() % 10 + 1;
        char op = opers[rand() % opers.size()];
        // 2、将数据推送到blockqueue
        Task t(x, y, op);
        bq->push(t);
        cout << pthread_self() << "| productor Task = " << t.formatArg() << endl;
        usleep(150000);
    }
}

int main(){

    srand((uint64_t)time(nullptr) ^ getpid());

    // BlockQueue<int> *bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    //单生产、单消费 -> 多生产、多消费
    pthread_t c[3], p[2];
    pthread_create(&c[0], nullptr, consumer, bq);
    pthread_create(&c[1], nullptr, consumer, bq);
    pthread_create(&c[2], nullptr, consumer, bq);
    pthread_create(&p[0], nullptr, productor, bq);
    pthread_create(&p[1], nullptr, productor, bq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);

    delete bq;

    return 0;
}
